import javax.swing.*;
import java.io.*;
public class LinkedListMain{
	public static Node head;
	public static Node rover;
	public static Node tail;
	public static Node roverx;
	public static int cnt = 0;
	public static void add(Node d){
		if(head == null){
			head = d;
			tail = d;
		}
		else{
			tail.next = d;
			tail = tail.next;
		}
		cnt++;
	}
	public static void all(){
		rover = head;
		while(rover != null){
			System.out.println("" + rover.name);
			rover = rover.next;
		}
	}
	public static boolean delete(String input){
		if(head.name.equals(input)){
			if(head.next != null){
				head = head.next;
				return true;
			}
			else{
				head = null;
				return true;
			}
		}
		else if(tail.name.equals(input)){
			rover = head;
			int a = 0;
			while(a < cnt - 1){
				rover = rover.next;
				a++;
			}
			tail = rover;
			return true;
		}
		rover = head;
		while(rover != null){
			if(rover.name.equals(head.next.name)){
				roverx = head;
			}
			if(rover.name.equals(input)){
				roverx.next = rover.next;
				return true;
			}
			roverx = rover;
			rover = rover.next;
		}
		return false;
	}
	public static boolean search(String xinput){
		rover = head;
		while(rover != null){
			if(rover.name.equals(xinput)){
				return true;
			}
			rover = rover.next;
		}
		return false;
	}
	public static void main(String args[]){
		JOptionPane.showMessageDialog(null, "Hello World!!!!");
		int a = 0;
		while(a == 0){
			int input = Integer.parseInt(JOptionPane.showInputDialog("1- Add Node\n2- Delete Node\n3- Search  by Name\n4- Save to File\n5- Load from File\n6- List all nodes\n7- End Program"));
			if(input == 1){
				int b = Integer.parseInt(JOptionPane.showInputDialog("Enter the ID of the node: "));
				String c = JOptionPane.showInputDialog("Enter the name of the node: ");
				Node d = new Node(b, c);
				add(d);
			}
			else if(input == 2){
				String xinput = JOptionPane.showInputDialog("Input the name of the Node to be deleted: ");
				boolean b = delete(xinput);
				if(b == true){
					JOptionPane.showMessageDialog(null, "Node deleted!");
				}
				else{
					JOptionPane.showMessageDialog(null, "NO such node in the list");
				}
			}
			else if(input == 3){
				String xinput = JOptionPane.showInputDialog("Input the name of the node to search: ");
				boolean xoutput = search(xinput);
				if(xoutput){
					JOptionPane.showMessageDialog(null, "There's a node with name like that one:");
				}
				else{
					JOptionPane.showMessageDialog(null, "No node like that one!");
				}
			}
			else if(input == 6){
				all();
			}
			else if(input == 7){
				a = 1;
			}

		}
	}
}